<template>
  <div class="root">
    <div class="top">
      <span>在线诊断</span>
    </div>
    <div class="mid">
      <Card_message_User v-for="(item,index) in messages" 
      :key="index" :message="item"/>
    </div>
    <div class="bottom">
      <div class="input">
        <el-input
          v-model="text"
          style="width: 1800px;font-size: 20px;"
          :autosize="{ minRows: 4, maxRows: 4 }"
          type="textarea"
          placeholder="请输入问题（可点击或拖拽至右方上传图片）"
          @keyup.enter="sendMessage">
        </el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>
    <el-upload
        class="upload-demo"
        drag
        :action="url"
        multiple
        :auto-upload="false"
        :before-upload="handleImages"
        ref="uploadRef"
        @keyup.enter="sendMessage"
      >
        <el-button type="primary">+&nbsp上传图片</el-button>
    </el-upload>
  </div>
</template>

<script setup>
import {ref,onMounted,onBeforeUnmount} from 'vue'
import Card_message_User from "@/components/Card_message_User.vue";
import { useRoute } from 'vue-router';
import { reqChatHistory } from '@/api/chat';

// const url=`ws://cgp788.natappfree.cc/consultation/true/${localStorage.getItem('UID')}`
const $route=useRoute()
const url='#'
// const socket = new WebSocket(`ws://zu6bci.natappfree.cc/consultation/true/${localStorage.getItem('DOCTORID')}`); // 使用WebSocket协议



// 判断是否是JSON消息
const isJSON=(str)=>{
  try{
    JSON.parse(str)
    return true
  }catch(e){
    return false
  }
}

// 存储服务器转发的消息
let message=ref()

let socket=null

onMounted(async () => {

  const uid=localStorage.getItem('UID')
  socket = new WebSocket(`ws://47.108.153.130:8090/consultation/true/${uid}`); // 使用WebSocket协议

  socket.onopen = () => {
    console.log('连接成功');
  };

  socket.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  socket.onclose = () => {
    console.log('连接关闭');
  };
  // 监听服务端发送的消息
  socket.onmessage = (event) => {
  console.log('收到消息:', event.data);
    
    message.value=event.data
    // 当从聊天记录页面跳转过来时不需要接收问候语
    if(message.value=='你好,有什么可以帮到你的吗?'){
      if(!$route.query.did){
        messages.value.push(message.value);
      }
    }else{
      if(isJSON(message.value)){
        message.value=JSON.parse(message.value)
      }
      messages.value.push(message.value);
    }
  };
  // 从聊天记录页面跳转过来的时候不需要添加问候语
  if($route.query.did){
    let res=await reqChatHistory(page.value,10,localStorage.getItem('UID'),$route.query.did)
    // let res=await reqChatHistory(page.value,5,localStorage.getItem('UID'),437)
    // let res=await reqChatHistory(page.value,5,2,2)
    // console.log(res)
      // 监听滚动事件
    window.addEventListener('scroll', handleScroll);
    if(res.data.code==1){
      messages.value=res.data.data.chatPageList
    }
  }
});

// onBeforeUnmount(() => {
//   // 组件卸载时关闭 WebSocket 连接
//   socket.close();
// });

let messages=ref([])
let text=ref('')

// 发送用户的文字
const uploadRef = ref()
const sendMessage=async (event)=>{
  // 阻止回车键默认打开文件列表的行为
  if (event) {
  // console.log(event)
    event.preventDefault(); // 阻止回车键的默认行为
  }

  if(text.value.trim()){
    const message = {
      value: text.value,
      isUser: true,
      type: 'font'
    };
    const obj={
      receiver:$route.query.doctorId||$route.query.did,
      content:text.value,
      sender:localStorage.getItem('UID'),
      type:0,
      user:true
    }
    socket.send(JSON.stringify(obj)); // 发送消息到服务器
    // console.log(obj)

    messages.value.push(message)
    text.value=''
  }
  // console.log(uploadRef.value)
  // uploadRef?.value?.submit()
  // uploadRef?.value?.clearFiles()
  if (uploadRef.value?.uploadFiles?.length > 0) {
    // 手动触发文件处理
    await Promise.all(
      uploadRef.value.uploadFiles.map(file => 
        handleImages(file.raw) // 直接处理原始文件
      )
    );
    uploadRef.value.clearFiles();
  }
}

// 发送图片前的钩子，将图片的Base64编码发送到另一个组件并渲染
const handleImages=async (file) => {
  // 创建FileReader对象
  const reader = new FileReader();
  // 文件读取完毕时触发
  reader.onload = (e) => {
    const imageData = e.target.result; // 获取图片的 Base64 数据
    const message = {
      value: imageData,
      isUser: true,
      type: 'image'
    };
    const obj={
      receiver:$route.query.doctorId||$route.query.did,
      content:imageData,
      sender:localStorage.getItem('UID'),
      type:1,
      user:true
    }
    socket.send(JSON.stringify(obj))//发送图片至服务端

    messages.value.push(message);
  };
  reader.readAsDataURL(file); // 异步读取文件内容，读取为Base64编码
  return false
}

// 页码
let page=ref(1)
// 滑动更新聊天记录
const handleScroll=async ()=>{
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  // console.log('scrollTop:', scrollTop);
  // console.log('scrollHeight:', scrollHeight);
  // console.log('clientHeight:', clientHeight);
  const did=$route.query.did
  if (scrollHeight - scrollTop <= clientHeight + 50&&did ) {
    page.value += 1;
    // let res=await reqChatHistory(page.value,5,2,2)
    let res=await reqChatHistory(page.value,5,localStorage.getItem('UID'),did)
    // console.log(res)
    if(res.data.code==1){
      messages.value=[...messages.value,...res.data.data.chatPageList]
      // console.log(messages.value)
    }
  }
}

</script>

<style lang="scss" scoped>
.root{
  min-width: 1810px;
  .top{
    background-color: #bbb;
    height: 50px;
    padding-left: 10px;
    // width: 1600px;
    span{
      font-size: 28px;
      line-height: 50px;
      margin-left: 30px;
    }
  }
  .mid{
    padding-left: 35px;
    padding-right: 85px;
    min-height: 600px;
    // width: 1600px;
  }
  .bottom{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    min-height:300px;
    margin-left: 50px;
    .input{
      display: flex;
      width: 800px;
      height: 100%;
      margin-left: -60px;
      .el-button{
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        right: 20px;
        bottom: 10px;
        border-radius: 12px;
        height: 40px;width: 70px;
        margin-top: 90px;
        margin-left: 20px;
      }
      .el-textarea{
        ::v-deep .el-textarea__inner{
          border-radius: 20px;
        }
      }
    }

  }
  .upload-demo{
      margin-left: 72%;
      margin-top: -125px;
      ::v-deep(.el-upload-dragger){
        background: transparent;
        width: 125px;
        height: 41px;
        border: none;
      }
      ::v-deep(ul){
        min-width: 100px;
        max-width: 300px;
      }
    }
}
</style>
